package com.qf.blog.commons.utils;

import com.alibaba.fastjson.JSON;
import com.qf.blog.dto.SensitiveWordResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class SensitiveWordDetector {
    @Value ("${SWService.url}")
    private String url;
    @Value ("${SWService.type}")
    private String type;
    @Value ("APPCODE ${SWService.appcode}")
    private String appcode;

    public SensitiveWordResp detect(String words) {
        HashMap<String, String> reqParams = new HashMap<>();
        HashMap<String, String> reqHeader = new HashMap<>();
        reqParams.put("type", type);
        reqParams.put("content", words);
        reqHeader.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        reqHeader.put("Authorization", appcode);
        String respStr = HttpClientUtils.postJson(url, reqHeader, getFormStr(reqParams));
        SensitiveWordResp resp = JSON.parseObject(respStr, SensitiveWordResp.class);
        return resp;
    }

    public String getFormStr(Map<String, String> map) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (sb.length() > 0) {
                sb.append("&");
            }
            try {
                sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"))
                        .append("=")
                        .append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
//throw new RuntimeException(e);
                e.printStackTrace();
            }
        }
        return sb.toString();
    }


}